let webSocket = null;

function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
        $("#conversation").show();
    }
    else {
        $("#conversation").hide();
    }
    $("#greetings").html("");
}

function connect() {
    let username = $("#username").val()
    console.log(`username = ${username}`)

    webSocket = new WebSocket(`ws://localhost:8080/spring-ws/${username}`)

    webSocket.onopen = () => {
        console.log("连接成功...")
        setConnected(true);
    }

    webSocket.onmessage =  (evt) => {
        let message = evt.data;
        showGreeting(message, true);
    };

    webSocket.onclose = () => {
        // 关闭 websocket
        setConnected(false);
        console.log("连接关闭...")
    };

    webSocket.onerror = () => {
        // 关闭 websocket
        setConnected(false);
        console.log("发生异常...")
    };
}

function sendName() {
    let message = $("#name").val()
    webSocket.send(JSON.stringify({'name': message}));
    showGreeting(message);
}

function disconnect() {
    webSocket.close()
}


function showGreeting(message, secret) {
    if (secret) {
        $("#greetings").append("<tr style='color: darkgoldenrod'><td>" + message + "</td></tr>");
    } else {
        $("#greetings").append("<tr><td>" + message + "</td></tr>");
    }

}

function login() {
    let username = $("#username").val()
    $("#member").text(username)
    $("#loginForm").hide()
    $("#usernameDiv").show()
}

$(function () {
    $("#loginForm").show()
    $("#usernameDiv").hide()
    $("#inputDiv").hide()


    $("form").on('submit', function (e) {
        e.preventDefault();
    });
    $( "#connect" ).click(function() { connect(); $("#inputDiv").show();});
    $( "#disconnect" ).click(function() { disconnect(); $("#inputDiv").hide();});
    $( "#send" ).click(function() { sendName(); });

    $( "#login" ).click(function() { login(); });

    $("#sendFile").click(function() {
        let file = $("#file")[0].files[0];

        console.log(file)

        // form.append("myfile", new Blob(file));

        uploader(file)
    });
});



class FileSlicer {
    constructor(file) {
        this.file = file;
        this.sliceSize = 4*1024;
        this.slices = Math.ceil(file.size / this.sliceSize);
        this.currentSlice = 0;
    }

    nextSlice(){
        let start = this.currentSlice * this.sliceSize;
        let end = Math.min((this.currentSlice+1) * this.sliceSize, this.file.size);
        this.currentSlice++;
        return this.file.slice(start, end);
    }

}

function uploader(file) {
    console.log("upload file size = "+file.size)

    let fs = new FileSlicer(file);
    for(let i = 0; i < fs.slices; ++i) {
        webSocket.send(new Blob(fs.nextSlice())); // see below
    }

}
